﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CounterServerModel;
using System.Data;
using CounterServerModel.Authentication;

namespace SmartCounters
{
	public partial class BillsManagement : System.Web.UI.Page
	{

		protected void Page_Load(object sender, EventArgs e)
		{
			((MainTemplate)Master).m_PagePermissionFilter = MainTemplate.k_AdminPageFilter;
		}

		protected void Page_Prerender(object sender, EventArgs e)
		{
			populateAccountsList();
			populateDropDownLists();
		}

		private void populateAccountsList()
		{
			InformationReader infoProvider = new InformationReader();
			DataTable accountsTable = new InformationReader().GetAccountsDataTable(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials);
			if (!IsPostBack)
			{
				foreach (DataRow account in accountsTable.Rows)
				{
					string accountLable = account["Country"] + " " + account["City"] + " " + account["street"] + " " + account["House"] + "/" + account["Apartment"];
					cbAssociatedAccounts.Items.Add(new ListItem(accountLable, account["AccountID"].ToString()));
				}
			}
		}

		protected void SendBills(object sender, EventArgs e)
		{
			List<Bill> bills = new List<Bill>();
			if (cbAssociatedAccounts.SelectedIndex == -1)
			{
				lblErrorText.Text = "You must select at leas one account.";
				return;
			}
			foreach (ListItem accountItem in cbAssociatedAccounts.Items)
			{
				if (accountItem.Selected)
				{
					int accountID = int.Parse(accountItem.Value);
					int year = int.Parse(ddYear.SelectedItem.Value);
					int month = int.Parse(ddMonth.SelectedItem.Value);

					try
					{
						BillingService billingService = new BillingService();
						Bill predictedBill = billingService.GetBillPrediction(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, accountID, year, month);
						bills.Add(predictedBill);
					}
					catch (Exception ex)
					{
						lblErrorText.Text = ex.Message;
						return;
					}

				}
			}

			Session[SendBillsForm.k_BillsToSendSessionKey] = bills;
			Response.Redirect("/Administration/SendBillsForm.aspx");

		}

		private void populateDropDownLists()
		{
			ddMonth.Items.Add(new ListItem("Select Month", "-1"));
			ddYear.Items.Add(new ListItem("Select Year", "-1"));

			int currentYear = DateTime.Now.Year;
			for (int i = -5; i < 5; i++)
			{
				ddYear.Items.Add(new ListItem((currentYear + i).ToString(), (currentYear + i).ToString()));
			}

			for (int i = 0; i < 12; i++)
			{
				DateTime tempDate = new DateTime(1900, i + 1, 1);
				ddMonth.Items.Add(new ListItem(tempDate.ToString("MMMM"), tempDate.Month.ToString()));
			}

		}
	}
}
